const Router = require('koa-router')
const axios = require('axios')
const OrderModel = require('../models/order')
const Order = require('../models/order')

const route = new Router({ prefix: '/api/order' })

route.post('/pay', async ctx => {
    const { openid } = ctx.request.body
    let res = {
        success: false,
        data: {},
        error: {},
        msg: ''
    }

    try {
        let response = await axios.post(
            'http://wx.xinglong.tech/pay',
            { openid }
        )
        res.data = response.data
        console.log('支付消息: ', res.data)
    } catch (error) {
        console.error(error)
    }

    ctx.body = res
})

/*
    "openid": "",
    "commodityList": [],
    "status": "",
    "address": "",
    "money": 100
*/

// 曾
route.put('/', async ctx => {
    let res = {
        success: false,
        data: {},
        error: {},
        msg: ''
    }
    const {
        openid, commodityList, status, address, money
    } = ctx.request.body
    try {
        res.data = await OrderModel.create({
            openid, commodityList, status, address, money
        })
        res.success = true
    } catch (error) {
        res.error = error
        ctx.status = 500
    }
    ctx.body = res
})
// 改


route.post('/', async ctx => {
    let res = {
        success: false,
        data: {},
        error: {},
        msg: ''
    }
    const {
        openid, commodityList, 
        status, address, money, _id
    } = ctx.request.body
    try {
        let order = await OrderModel.findById(_id)
        order.set({
            openid, commodityList, 
            status, address, money,
        })
        await order.save()
        res.success = true
    } catch (error) {
        res.error = error
        ctx.status = 500
    }
    ctx.body = res
})

// 删
route.delete('/', async (ctx) => {
    let res = {
        success: false,
        data: {},
        error: {},
        msg: ''
    }
    try {
        const { id } = ctx.query
        let order = await OrderModel.findById(id)
        order.set({
            isDelete: true
        })
        await order.save()
        res.success = true
    } catch (error) {
        res.error = error
        ctx.status = 500
    }
    ctx.body = res
})

// 查
route.get('/', async (ctx) => {
    let res = {
        success: false,
        data: {},
        error: {},
        msg: ''
    }

    let condition = {
        isDelete: false
    }
    try {
        const { openid, status } = ctx.query
        condition.openid = openid
        if (status) {
            condition.status = status
        }
        res.data = await OrderModel.find(condition)
        res.success = true
    } catch (error) {
        res.error = error
        ctx.status = 500
    }
    ctx.body = res
})

module.exports = route
